/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.CoursechapterresourcesQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author shitou
* @date 2024-12-12
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "课程章节资源管理")
@RequestMapping("/api/coursechapterresources")
public class CoursechapterresourcesController {

    private final CoursechapterresourcesService coursechapterresourcesService;

    private final CoursechapterService coursechapterService;

    private final CoursechapterexercisesetService coursechapterexercisesetService;

    private final CourseresourcesmsgService courseresourcesmsgService;

    private final ExercisesetService exercisesetService;

    private final StudentService studentService;

    private final StudentchapterresourcestaskService studentchapterresourcestaskService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('coursechapterresources:list')")
    public void exportCoursechapterresources(HttpServletResponse response, CoursechapterresourcesQueryCriteria criteria) throws IOException {
        coursechapterresourcesService.download(coursechapterresourcesService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询课程章节资源")
    @ApiOperation("查询课程章节资源")
//    @PreAuthorize("@el.check('coursechapterresources:list')")
    public ResponseEntity<PageResult<Coursechapterresources>> queryCoursechapterresources(CoursechapterresourcesQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(coursechapterresourcesService.queryAll(criteria,page),HttpStatus.OK);
    }

    @GetMapping("/getChpaterResourcesMsg")
    public ResponseEntity<Map<String,Object>> getChpaterResourcesMsg(CoursechapterresourcesQueryCriteria criteria){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",criteria.getCourseChapterId());
        Coursechapter coursechapter = coursechapterService.getOne(queryWrapper);
        Map<String,Object>  map = new HashMap<>();
        map.put("name",null);
        map.put("id",null);
        map.put("content",null);

        map.put("resourcesList",new ArrayList<>());
        map.put("imgArr",new ArrayList<>());
        map.put("videoArr",new ArrayList<>());
        map.put("wordArr",new ArrayList<>());
        map.put("workArr",new ArrayList<>());
        map.put("exercisesetList",new ArrayList<>());
        //获取所有资源
        List<Courseresourcesmsg> msgList = courseresourcesmsgService.list();

        if(coursechapter!=null){

            map.put("name",coursechapter.getName());
            map.put("id",coursechapter.getId());
            map.put("content",coursechapter.getContent());
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("courseChapterId",criteria.getCourseChapterId());
            List<Coursechapterresources> list = coursechapterresourcesService.list(queryWrapper1);

            List<Coursechapterresources> imgArr = new ArrayList<>();
            List<Coursechapterresources> videoArr = new ArrayList<>();
            List<Coursechapterresources> wordArr = new ArrayList<>();
            List<Coursechapterresources> workArr = new ArrayList<>();
//            map.put("resourcesList",list);

            for(Coursechapterresources coursechapterresources:list){
                for(Courseresourcesmsg courseresourcesmsg:msgList){
                    if(coursechapterresources.getCourseResourcesMsgId() == courseresourcesmsg.getId()){
                        coursechapterresources.setUrl(courseresourcesmsg.getUrl());
                    }
                }
                if(coursechapterresources.getType() == 0){
                    imgArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 1){
                    videoArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 2){
                    wordArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 4){
                    workArr.add(coursechapterresources);
                }
            }
            map.put("imgArr",imgArr);
            map.put("videoArr",videoArr);
            map.put("wordArr",wordArr);
            map.put("workArr",workArr);


            //获取习题集资源
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("courseChapterId",criteria.getCourseChapterId());
            List<Coursechapterexerciseset>  list2 = coursechapterexercisesetService.list(queryWrapper2);

            List<Integer> exercisesetIds = new ArrayList<>();
            for(Coursechapterexerciseset coursechapterexerciseset:list2){
                exercisesetIds.add(coursechapterexerciseset.getExercisesetId());
            }
            if(exercisesetIds.size()!=0){

                QueryWrapper queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.in("id",exercisesetIds);
                List<Exerciseset> exercisesetList = exercisesetService.list(queryWrapper3);
                System.out.println("====="+exercisesetList);
                for(Exerciseset exerciseset:exercisesetList){
                    for(Coursechapterexerciseset coursechapterexerciseset:list2){
                        if(exerciseset.getId() == coursechapterexerciseset.getExercisesetId()){
                            coursechapterexerciseset.setName(exerciseset.getName());
                        }
                    }
                }
            }
            map.put("exercisesetList",list2);
        }
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    @GetMapping("/getStudentChpaterResourcesMsg")
    public ResponseEntity<Map<String,Object>> getStudentChpaterResourcesMsg(CoursechapterresourcesQueryCriteria criteria){



        QueryWrapper queryWrapperStudent = new QueryWrapper<>();
        queryWrapperStudent.eq("userId", SecurityUtils.getCurrentUserId());
        List<Student> studentList = studentService.list(queryWrapperStudent);
        Student student = studentList.get(0);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",criteria.getCourseChapterId());
        Coursechapter coursechapter = coursechapterService.getOne(queryWrapper);
        Map<String,Object>  map = new HashMap<>();
        map.put("name",null);
        map.put("id",null);
        map.put("content",null);

        map.put("resourcesList",new ArrayList<>());
        map.put("imgArr",new ArrayList<>());
        map.put("videoArr",new ArrayList<>());
        map.put("wordArr",new ArrayList<>());
        map.put("workArr",new ArrayList<>());
        map.put("exercisesetList",new ArrayList<>());
        //获取所有资源
        List<Courseresourcesmsg> msgList = courseresourcesmsgService.list();

        if(coursechapter!=null){

            map.put("name",coursechapter.getName());
            map.put("id",coursechapter.getId());
            map.put("content",coursechapter.getContent());
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("courseChapterId",criteria.getCourseChapterId());
            List<Coursechapterresources> list = coursechapterresourcesService.list(queryWrapper1);

            List<Coursechapterresources> imgArr = new ArrayList<>();
            List<Coursechapterresources> videoArr = new ArrayList<>();
            List<Coursechapterresources> wordArr = new ArrayList<>();
            List<Coursechapterresources> workArr = new ArrayList<>();
//            map.put("resourcesList",list);

            for(Coursechapterresources coursechapterresources:list){
                for(Courseresourcesmsg courseresourcesmsg:msgList){
                    if(coursechapterresources.getCourseResourcesMsgId() == courseresourcesmsg.getId()){
                        coursechapterresources.setUrl(courseresourcesmsg.getUrl());
                    }
                }
                if(coursechapterresources.getType() == 0){
                    imgArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 1){
                    videoArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 2){
                    wordArr.add(coursechapterresources);
                } else if(coursechapterresources.getType() == 4){
                    workArr.add(coursechapterresources);
                }
            }
            if(workArr.size()!=0){
                List<Integer> courseChapterResourecesIdList = new ArrayList<>();
                for(Coursechapterresources coursechapterresources:workArr){
                    courseChapterResourecesIdList.add(coursechapterresources.getId());
                }
                QueryWrapper queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.in("courseChapterResourecesId",courseChapterResourecesIdList);
                queryWrapper2.eq("studentId",student.getId());
                List<Studentchapterresourcestask> studentchapterresourcestaskList = new ArrayList<>();
                if(courseChapterResourecesIdList.size()!=0){
                    studentchapterresourcestaskList = studentchapterresourcestaskService.list(queryWrapper2);

                    for(Coursechapterresources coursechapterresources:wordArr){
                        List<Studentchapterresourcestask> studentchapterresourcestaskList1 = new ArrayList<>();
                        for(Studentchapterresourcestask studentchapterresourcestask:studentchapterresourcestaskList){
                            if(coursechapterresources.getId() == studentchapterresourcestask.getCourseChapterResourcesId()){
                                studentchapterresourcestaskList1.add(studentchapterresourcestask);
                            }
                        }
                        coursechapterresources.setStudentchapterresourcestaskList(studentchapterresourcestaskList1);
                    }
                }
            }
            map.put("imgArr",imgArr);
            map.put("videoArr",videoArr);
            map.put("wordArr",wordArr);
            map.put("workArr",workArr);


            //获取习题集资源
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("courseChapterId",criteria.getCourseChapterId());
            List<Coursechapterexerciseset>  list2 = coursechapterexercisesetService.list(queryWrapper2);

            List<Integer> exercisesetIds = new ArrayList<>();
            for(Coursechapterexerciseset coursechapterexerciseset:list2){
                exercisesetIds.add(coursechapterexerciseset.getExercisesetId());
            }
            if(exercisesetIds.size()!=0){

                QueryWrapper queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.in("id",exercisesetIds);
                List<Exerciseset> exercisesetList = exercisesetService.list(queryWrapper3);

                for(Exerciseset exerciseset:exercisesetList){
                    for(Coursechapterexerciseset coursechapterexerciseset:list2){
                        if(exerciseset.getId() == coursechapterexerciseset.getExercisesetId()){
                            coursechapterexerciseset.setName(exerciseset.getName());
                        }
                    }
                }
            }
            map.put("exercisesetList",list2);
        }
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

//    @PostMapping
//    @Log("新增课程章节资源")
//    @ApiOperation("新增课程章节资源")
////    @PreAuthorize("@el.check('coursechapterresources:add')")
//    public ResponseEntity<Object> createCoursechapterresources(@Validated @RequestBody Coursechapterresources resources){
//        coursechapterresourcesService.create(resources);
//        return new ResponseEntity<>(HttpStatus.CREATED);
//    }

    @PostMapping
    @Log("新增课程章节资源")
    @ApiOperation("新增课程章节资源")
//    @PreAuthorize("@el.check('coursechapterresources:add')")
    public ResponseEntity<Object> createCoursechapterresourcesArr(@RequestBody Coursechapterresources resources){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",resources.getType());
        queryWrapper.eq("courseChapterId",resources.getCourseChapterId());
        coursechapterresourcesService.remove(queryWrapper);
        if(resources.getCourseResourcesMsgIdArr()!=null && resources.getCourseResourcesMsgIdArr().size()!=0){
            for(Integer item:resources.getCourseResourcesMsgIdArr()){
                resources.setId(null);
                resources.setCourseResourcesMsgId(item);
                coursechapterresourcesService.create(resources);
            }
        }


        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改课程章节资源")
    @ApiOperation("修改课程章节资源")
//    @PreAuthorize("@el.check('coursechapterresources:edit')")
    public ResponseEntity<Object> updateCoursechapterresources(@Validated @RequestBody Coursechapterresources resources){
        coursechapterresourcesService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除课程章节资源")
    @ApiOperation("删除课程章节资源")
//    @PreAuthorize("@el.check('coursechapterresources:del')")
    public ResponseEntity<Object> deleteCoursechapterresources(@RequestBody List<Integer> ids) {
        coursechapterresourcesService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}